<template>
  <svg 
    xmlns="http://www.w3.org/2000/svg"
    version="1.1"
    class="line"
    :width="`${width}px`" 
    :height="`${height}px`"
    :style="style"
    :viewBox="viewBox">
    <line
      :x1="start.x" 
      :y1="start.y" 
      :x2="end.x" 
      :y2="end.y" 
      :stroke="color"
      stroke-width="3"
      fill="transparent"/>
  </svg>
</template>

<script>
export default {
  name: 'LeaderLine',
  props: {
    start: {
      type: Object,
      validator: pointValidator
    },
    end: {
      type: Object,
      validator: pointValidator
    },
    color: {
      type: String,
      default: '#ccc'
    }
  },
  computed: {
    minX () {
      return Math.min(this.start.x, this.end.x)
    },
    minY () {
      return Math.min(this.start.y, this.end.y)
    },
    // 坐标差
    diffX () {
      return Math.abs(this.start.x - this.end.x)
    },
    diffY () {
      return Math.abs(this.start.y - this.end.y)
    },
    width () {
      return this.diffX
    },
    height () {
      return this.diffY
    },
    viewBox () {
      // 最小X轴数值；最小y轴数值；宽度；高度
      return `${this.minX} ${this.minY} ${this.width} ${this.height}`
    },
    style () {
      return {
        left: this.minX + 'px',
        top: this.minY  + 'px',
      }
    }
  }
}

function pointValidator (point) {
  return isNumber(point.x) && isNumber(point.y)
}
function isNumber(obj) {
  return obj === +obj
}
</script>

<style lang="scss" scoped>
.line {
  position: absolute;
}
</style>
